import { DeviceDeviceService } from './../device/service/device';
import { CoolEvent, Event } from '@cool-midway/core';
import { Inject } from '@midwayjs/core';
import { PluginService } from '../plugin/service/info';
import { EVENT_PLUGIN_READY } from '../plugin/service/center';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { DeviceDeviceEntity } from '../device/entity/device';
import { Repository } from 'typeorm';
// import { OrderOrderEntity } from '../order/entity/order';

//娃娃机 "baseUrl": "mqtt://39.108.162.25:1883",
/**
 * MQTT事件
 */
@CoolEvent()
export class DemoQmttEvent {
  @Inject()
  pluginService: PluginService;

  @InjectEntityModel(DeviceDeviceEntity)
  DeviceDeviceEntity: Repository<DeviceDeviceEntity>;

  // @InjectEntityModel(OrderOrderEntity)
  // OrderOrderEntity: Repository<OrderOrderEntity>;

  /**
   * 插件已就绪
   */
  @Event(EVENT_PLUGIN_READY)
  async pluginReady(keyName: string) {
    console.log('阿什顿开发哈收款到',keyName);
    
    // 如果是mqtt插件
    if (!keyName || keyName == 'mqtt') {
      // 获取插件实例
      const instance = await this.pluginService.getInstance('mqtt');


      // 监听是否连接成功
      instance.onEvent('connect', () => {
        console.log('connectconnectconnectconnectconnectconnect');
        // 连接成功后订阅消息
        instance.subscribe('$thing/up/property/hqwkq123/#');
      });
      instance.onEvent('error', (error) => {
        console.log('errorerrorerrorerrorerrorerrorerror', error);
      });
      instance.onEvent('offline', () => {
        console.log('close');
      });
      // // 监听消息
      instance.onEvent('message', async (topic, msg) => {
        /* 拆解$thing/up/property/hqwkq123/863644073570286/主题，获取到对应的imei号 */
        const imei = topic.trim().split('/')[4];

        const content = JSON.parse(msg.toString());

        console.log("收到消息", { content, topic });
        /* 收到心跳 */
        if (content.HeatBit_count) {
        } else if (Object.keys(content)?.length > 0) {
          /* 如果收到设备的消息上报 */
          /* 如果找到对应的设备 */

          console.log('imeiimeiimeiimeiimei', imei);

          if (imei) {
            const _device = await this.DeviceDeviceEntity.findOneBy({ imei });

            if (_device) {
              /* 更新设备状态 */
              await this.DeviceDeviceEntity.update(
                { imei },
                { status: 0, ...content }
              );
            }
          }
        }

        // console.log(
        //   'MQtt消息回来了啊啊啊=>',
        //   '主题是',
        //   topic,
        //   '内容是',
        //   JSON.parse(msg.toString()),
        //   'imei',
        //   // imei,
        //   "topic.split('/')"
        //   // JSON.parse(topic.toString()).split('/')[5]
        // );
      });
    }
  }
}
